<template>
   <el-drawer
    :title="title"
    :visible.sync="dialogVisible"
    width="20%"
    :close-on-click-modal="false"
    :before-close="handleClose">
    <el-form :model="userForm" ref="userForm" :rules="rules" label-width="100px">
      <el-form-item label="账号:" prop="username">
        <el-input v-model="userForm.username" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item label="头像:">
        <UploadImageFile
        :limit="1"
        :uploadValue.sync="uploadImages"/>
      </el-form-item>
      <el-form-item label="手机号:">
        <el-input v-model.trim="userForm.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="角色:">
        <el-select v-model="userForm.roleIds" multiple placeholder="请选择" style="width: 100%;">
          <el-option
            v-for="item in roles"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="密码:" :prop="inputPwd? 'password' : ''">
        <el-input v-model.trim="userForm.password" type="password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码:" :prop="inputPwd? 'surePassword' : ''">
        <el-input v-model.trim="userForm.surePassword" type="password" placeholder="请输入确认密码"></el-input>
      </el-form-item>
      <el-form-item label="启用状态">
        <EnabledSwitch :value.sync="userForm.isEnabled"/>
      </el-form-item>
    </el-form>

    <span class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="confirm">确 定</el-button>
    </span>
  </el-drawer>
</template>
<script>
import UploadImageFile from '@/components/UploadImageFile/index.vue'
import EnabledSwitch from '@/components/EnabledSwitch/index.vue'

import { userAdd, userEdit, userDetail } from '@/api/user'
import { roleList } from '@/api/role'

export default {
  name: 'AddUser',
  components: {
    UploadImageFile,
    EnabledSwitch
  },
  props: {
    rowId:{
      type: Number,
      default: ()=> null
    },
    title: {
      type: String,
      default: ()=> null
    },
    showDialog: {
      type: Boolean,
      default: ()=> false
    }
  },
  computed: {
    dialogVisible: {
      get(){
        return this.showDialog
      }
    }
  },
  data() {
    return {
      userForm: null,
      loading: false,
      inputPwd: true,
      initForm: {
        username: '',
        password: '',
        surePassword: '',
        phone: '',
        headImage: '',
        isEnabled: 1,
        roleIds: []
      },
      rules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur, change' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur, change' }],
        surePassword: [{ required: true, message: '请输入确认密码', trigger: 'blur, change' }]
      },
      uploadImages: [],
      roles: []
    }
  },
  watch: {
    rowId: {
      handler(rowId) {
        if(!rowId || rowId <= 0) {
          this.inputPwd = true
          return
        }
        this.inputPwd = false
        this.loadUserDetailData(rowId)
      }
    }
  },
  created(){
    this.userForm = { ...this.initForm }
    this.loadRoleListData()
  },
  methods: {
    // 角色列表
    async loadRoleListData(){
      const res = await roleList()
      this.roles = res.data
    },

    // 详情
    async loadUserDetailData(rowId){
      const res = await userDetail(rowId)
      this.userForm = { ...res.data }
      this.userForm.password = void 0
      const { roleVos, headImage } = res.data
      if(roleVos && roleVos.length > 0){
        this.userForm.roleIds = roleVos.map(item=> item.id)
      }
      if(headImage){
        this.uploadImages.push(headImage)
      }
    },

    // 关闭弹窗
    handleClose() {
      this.$emit('update:showDialog', false)
      this.$emit('update:rowId', null)
      this.$emit('update:title', null)
      this.uploadImages = []
      this.loading = false
      this.userForm = { ...this.initForm }
      this.$refs.userForm.resetFields()
    },

    // 提交数据
    confirm(){
      this.$refs.userForm.validate(async (valid) => {
        if(valid){
          try{
            this.loading = true
            if(this.uploadImages) this.userForm.headImage = this.uploadImages[0]
            if(this.userForm.surePassword || this.userForm.password) {
              if(this.userForm.surePassword !== this.userForm.password){
                this.$message.error('密码不一致')
                throw '密码不一致';
              }
            }
            if(!this.rowId){
              await userAdd(this.userForm)
            this.handleClose()
            }else {
              await userEdit(this.userForm)
              this.handleClose()
            }
            this.$emit('reloadData')
          }catch(e){
            this.loading = false
          }
        }else {
          console.log('error submit!!');
          this.loading = false
          return false;
        }
      });
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/drawer-page.scss'
</style>